package com.seiko.danmaku.factory

import android.net.Uri
import android.util.Log
import com.seiko.danmaku.DanmaResultBean
import com.seiko.danmaku.data.model.Result
import com.seiko.danmaku.data.repo.SmbMd5Repository
import com.seiko.danmaku.data.repo.SmbMrlRepository
import com.seiko.danmaku.domain.GetDanmaResultUseCase
import java.io.FileNotFoundException
import javax.inject.Inject

class DanmaResultWithFtp @Inject constructor(
    private val getResult: GetDanmaResultUseCase,
    private val smbMd5Repo: SmbMd5Repository,
    private val smbMrlRepo: SmbMrlRepository
) : IDanmaResult {

    override suspend fun decode(videoUri: Uri, isMatched: Boolean): Result<DanmaResultBean> {
        Log.w("DANMAKUUri",  videoUri.toString())
        val urlValue = videoUri.toString()
        val lastIndex: Int = urlValue.lastIndexOf('/')
        var fileName = "";
        if (lastIndex != -1) {
            fileName = urlValue.substring(lastIndex + 1)
        }
        // 先从数据去查找是否与此url匹配的MD5，没有则连接SMB去获取。
        if ((!fileName.contains("VLC") || !fileName.contains("XINLI")) && !fileName.contains(".") ) {
            return Result.Error(FileNotFoundException("title mismatch"))
        }
        val title = fileName.split(".")
        var ii = 0;
        for (i in 0 until title.size) {
            ii = i;
            if ("VLC".equals(title[i])) {
                break;
            }
            if ("XINLI".equals(title[i])) {
                break;
            }
        }
        var name = ""
        var episode = ""
        if (ii == 0 && ii + 1 < title.size) {
            name = title[ii + 1]
            episode = title[ii + 1]
        }
        if (ii == 0 && ii + 1 == title.size) {
            return Result.Error(FileNotFoundException("title mismatch"))
        }
        if (ii > 0 && ii + 1 < title.size){
            name = title[ii - 1]
            episode = title[ii + 1]
        }
        if (ii > 0 && ii + 1 == title.size){
            name = title[ii - 1]
            episode = title[ii - 1]
        }
        if (ii == title.size - 1 && (ii - 1) >= 0) {
            name = title[ii - 1]
            episode = title[ii - 1]
        }
        if (ii == title.size - 1 && (ii - 1) < 0) {
            return Result.Error(FileNotFoundException("title mismatch"))
        }

        return getResult.invoke(name, episode)
    }
}